//
//  HXTitleCollectionViewLayout.m
//  Homework_15
//
//  Created by 徐昊 on 16/8/3.
//  Copyright © 2016年 徐昊. All rights reserved.
//

#import "HXTitleCollectionViewLayout.h"

@interface HXTitleCollectionViewLayout ()
@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *attributesArray;
@property (nonatomic, assign) CGFloat contentWidth;
@end
@implementation HXTitleCollectionViewLayout
- (instancetype)init {
    self = [super init];
    if (self) {
        _attributesArray = [NSMutableArray array];
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        _attributesArray = [NSMutableArray array];
    }
    return self;
}
#pragma mark - 重写layout必须实现的三个方法
/** 计算每个item的大小 */
- (void)prepareLayout {
    CGFloat width = 0;
    CGFloat x = 0;
    for (int i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];
        // 创建系统需要的布局描述类
        UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:index];
        x = x + width;
        CGFloat y = 0;
        width = [self.delegate collectionView:self.collectionView layout:self height:45 heightForItemAtIndexPath:index] + 20;
        CGFloat height = 45;
        _contentWidth = x + width;
        layoutAttributes.frame = CGRectMake(x, y, width, height);
        [_attributesArray addObject:layoutAttributes];
    }
}
/** 返回每个item对应的布局属性 */
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return _attributesArray;
}
/** 负责collectionView的滚动范围 */
- (CGSize)collectionViewContentSize {
    return CGSizeMake(_contentWidth, 0);
}
@end
